package com.hong.concurrent.chapter6;

import java.util.Random;

/**
 * @Author csh
 * @Description  写的工作
 * @Date 2018/7/1 16:18
 */
public class WriterWorker extends Thread{
    /**
     * 随机数
     */
    private static final Random random= new Random(System.currentTimeMillis());
    /**
     * 数据
     */
    private final ShareData data;
    /**
     *  统计写次数
     */
    private final String filler;

    private int index = 0;

    public WriterWorker(ShareData data, String filler) {
        this.data = data;
        this.filler = filler;
    }

    @Override
    public void run() {
        try {
            while (true){
                char c = nextChar();
                data.write(c);
                Thread.sleep(random.nextInt(1000));
            }
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private char nextChar(){
        char c = filler.charAt(index);
        index++;
        if(index>=filler.length()){
            index=0;
        }
        return c;
    }
    public char[] read() throws InterruptedException {
        return data.read();
    }

    public void write(char c) throws InterruptedException {
        data.write(c);
    }

    public static void main(String[] args) {

    }
}
